package com.ekgc.addressbook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ekgc.addressbook.common.UserGroup;
import com.ekgc.addressbook.dao.mapper.ContactGroupRelationMapper;
import com.ekgc.addressbook.dao.mapper.ContactMapper;
import com.ekgc.addressbook.dao.mapper.GroupMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Slf4j
@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private ContactGroupRelationMapper contactGroupRelationMapper;


    @Autowired
    private ContactMapper contactMapper;

    @Override
    public List<UserGroup> getDataFromDatabase(String PhoneNumber) {
        return groupMapper.selectData(PhoneNumber);
    }


    @Override
    public boolean deleteGroupAndRelation(String phoneNumber, Integer userId) {
        // 根据手机号码和 userid 查询用户组的主键 id
        Integer groupId = groupMapper.findGroupIdByPhoneNumberAndUserId(phoneNumber, userId);
        if (groupId != null) {
            // 根据用户组的主键 id 删除联系人 - 分组关联表的数据
            int relationDeleteCount = groupMapper.deleteContactGroupRelationByGroupId(groupId);
            // 根据用户组的主键 id 删除用户组表的数据
            int groupDeleteCount = groupMapper.deleteUserGroupByGroupId(groupId);
            return relationDeleteCount >= 0 && groupDeleteCount > 0;
        }
        return false;
    }

    @Override
    public int addUserGroup(UserGroup userGroup) {
        try {
            return groupMapper.insertUserGroup(userGroup);
        } catch (Exception e) {
            log.error("Error inserting user group: {}", e.getMessage(), e);
            return 0;
        }
    }

    @Override
    public int deleteUserGroup(Integer groupId) {
        // 执行删除（注意：若有关联表，需先删除关联数据，避免外键约束）
        // 示例：先删除 contact_group_relation 中的关联记录（可选，根据业务需求）
        // contactGroupRelationMapper.deleteByGroupId(groupId);
        return groupMapper.deleteUserGroupById(groupId);
    }

    @Override
    @Transactional
    public void deleteGroup(int groupId) {
        try {
            // 先更新 contact_group_relation 表中关联记录的 group_id 为 0
            int updatedContactGroupCount = contactGroupRelationMapper.updateContactGroupIdToZero(groupId);
            log.info("Updated {} records in contact_group_relation table for groupId: {}", updatedContactGroupCount, groupId);
            // 再更新 contacts 表中关联记录的 groupid 为 0
            int updatedContactsCount = contactMapper.updateGroupIdToZero(groupId);
            log.info("Updated {} records in contacts table for groupId: {}", updatedContactsCount, groupId);
            // 最后删除 user_group 表中的分组记录
            groupMapper.deleteGroupById(groupId);
            log.info("Deleted group with groupId: {}", groupId);
        } catch (Exception e) {
            log.error("Error deleting group with groupId: {}", groupId, e);
            throw e;
        }
    }



        @Override
        public Integer getOrCreateGroup(Integer userId, String groupName) {
            // 查询是否存在该分组
            QueryWrapper<UserGroup> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId).eq("group_name", groupName);
            UserGroup group = groupMapper.selectOne(wrapper);

            if (group != null) {
                return group.getId();
            }

            // 不存在则创建新分组
            UserGroup newGroup = new UserGroup();
            newGroup.setUserId(userId);
            newGroup.setGroupName(groupName);
            groupMapper.insert(newGroup);

            return newGroup.getId();
        }

}